<template>
    <div>
        <el-button :disabled="formLoading" type="primary" @click="handle">汇总生成</el-button>
        <el-button @click="exportToExcel">导出为 Excel</el-button>
        <div v-for="(item, index) in state.list" :key="index">
            <el-form
                :model="item"
                :rules="formRules"
                label-width="100px"
                :ref="`form-${index}`"
            >
            <el-row :gutter="20" style="margin-bottom: 10px;">
                <el-col :span="6">
                    <el-form-item label="类型" prop="type">
                        <el-select
                            v-model="item.type"
                            clearable
                            placeholder="请选择类型"
                            @change="handleChange($event,item)"
                        >
                            <el-option
                                v-for="dict in state.optionsType"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-button :disabled="formLoading" type="primary" @click="handleAdd(index)">添加</el-button>
                    <el-button v-if="index" :disabled="formLoading" type="danger" @click="handleDelete(index)">删除
                    </el-button>
                </el-col>
            </el-row>
            <FourParams v-if="item.type === 1" :key="index" :ref="'FourParamsRef' + index" v-model="item.itemForm"
                        :mode="true"></FourParams>
            <maxParams v-if="item.type === 2" :key="index"  :ref="'maxParamsRef' + index" v-model="item.itemForm"
                       :mode="true"></maxParams>
            <translate v-if="item.type === 3" :key="index"  :ref="'translateRef' + index" v-model="item.itemForm" v-model:tableData="item.tableData"
                       :mode="true"></translate>
            </el-form>
        </div>
        <div>
            <el-table :data="tableData" height="80vh">
                <!-- 添加序号列 -->
                <el-table-column type="index" label="序号" width="200"></el-table-column>
                <el-table-column v-for="item in columnData" :key="item.prop" :label="item.label" :prop="item.prop">
                    <template #header="scope">
                        <div class="custom-header">
                            <div @click="handleCopy(scope)" style="color: #409EFF;">复制</div>
                            <span>{{ scope.column.label }}</span>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>


<script lang="ts" setup>
import {getCurrentInstance, onMounted, onUnmounted, reactive, ref} from "vue";
import FourParams from './FourParams.vue'
import maxParams from './maxParams.vue'
import translate from './translate.vue'
import {copyValue, generateRandomCancerTypes, generateRandomNumbers} from "@/views/Home/index";
import XEUtils from "xe-utils";
import * as XLSX from "xlsx";
import {saveAs} from 'file-saver';
const formRules = reactive({
    type: [{ required: true, message: "不能为空", trigger: "blur" }],
});
const state = reactive({
    list: [{
        itemForm: {},
        tableData: []
    },{
        itemForm: {},
        tableData: []
    }],
    optionsType: [
        {
            label: '平均值',
            value: 1
        },
        {
            label: '随机数',
            value: 2
        },
        {
            label: '翻译',
            value: 3
        }
    ]
})

const columnData = ref([
    {prop: 'num', label: '数量'},
]);
const tableData = ref([]);
const {proxy} = getCurrentInstance()
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const handleAdd = (index) => {
    state.list.splice(index + 1, 0, {
        itemForm: {},
        tableData: []
    });
}
const handleDelete = (index) => {
    state.list.splice(index, 1)
}
const handleChange = (val,item) => {
    item.itemForm = {}
}
const validate = async () => {
    const formRefs = proxy.$refs;
    let allValid = true; // 用于标记所有表单是否都通过校验

    // 遍历所有表单并校验
    for (const key in formRefs) {
        if (formRefs[key][0] && formRefs[key][0]?.validate) {
            const isValid = await formRefs[key][0].validate()
            if (!isValid) {
                allValid = false; // 如果任何一个表单未通过校验，将 allValid 设置为 false
            }
        }
    }
    return allValid
}

const handle = async () => {
    const formRefs = proxy.$refs;
    let allValid = true; // 用于标记所有表单是否都通过校验
    for (const key in formRefs) {
        if (formRefs[key][0] && formRefs[key][0]?.validate) {
            const isValid = await formRefs[key][0].validate()
            if (!isValid) {
                allValid = false; // 如果任何一个表单未通过校验，将 allValid 设置为 false
            }
        }
    }
    let arr = []
    for (let i = 0; i < 300; i++) {
        arr.push({})
    }
    let col = []
    for (let i = 0; i < state.list.length; i++) {
       let item = state.list[i]
        if (item.type === 1) {
            let item1 = generateRandomNumbers(item.itemForm)
            item1.forEach((j,ide) => {
                if (!arr[ide]['item' + i]) {
                    arr[ide]['item' + i] = j
                }
            })
        }
        if (item.type === 2) {
            let map = item.itemForm.map(j => {
                return Array(j.count).fill(j.name)
            })
            let item2 = generateRandomCancerTypes(XEUtils.flatten(map))
            item2.forEach((j,ide) => {
                if (!arr[ide]['item' + i]) {
                    arr[ide]['item' + i] = j
                }
            })
        }
        if (item.type === 3) {
            let item3 = item.tableData.map(j => {
                let find = item.itemForm.find(k => k.count == j.count)
                if (find) {
                    return {
                        count: j.count,
                        name: find.name
                    }
                }
            })
            item3.forEach((j,ide) => {
                if (!arr[ide]['item' + i]) {
                    arr[ide]['item' + i] = j.name
                }
            })
        }
        col.push({prop: `item${i}`, label: `值${i}`})
    }
    columnData.value = col
    tableData.value = arr

    let result = '';

    tableData.value.forEach(item => {
        let str = col.map(j => j.prop)
        let resultItem = '';
        str.forEach((key, index) => {
            resultItem += `${item[key] || ''}`; // 获取对象中对应键的值
            if (index < str.length - 1) {
                resultItem += '\t'; // 在最后一个键值对之前添加制表符
            }
        });
        resultItem += '\n'; // 在末尾添加换行符
        result += resultItem
        // result += `${item['item0']}\t${item['item1']}\t${item['item2']}\n`;
    });
    copyValue(result)
    console.log(result);
    console.log(state.list)
    console.log(123)
}
const resetTableData = () => {
    const propToLabelMap = new Map(columnData.value.map(item => [item.prop, item.label]));
    const restructuredTableData = tableData.value.map(row => {
        const newRow = {};
        for (const prop in row) {
            if (row.hasOwnProperty(prop) && propToLabelMap.has(prop)) {
                newRow[propToLabelMap.get(prop)] = row[prop];
            }
        }
        return newRow;
    });
    return restructuredTableData;
};
const exportToExcel = () => {
    const newTableData = resetTableData();
    const worksheet = XLSX.utils.json_to_sheet(newTableData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    const excelBuffer = XLSX.write(workbook, {
        bookType: 'xlsx',
        type: 'array',
    });
    const data = new Blob([excelBuffer], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
    });
    saveAs(data, 'tableData.xlsx');
};
const handleCopy = (scope) => {
    console.log(scope.column.property);
    let fil =  tableData.value.filter(j => {
        if (j[scope.column.property]) {
            return j
        }
    })
    let map =fil.map(j => j[scope.column.property]).join("\n");
    copyValue(map)
}
onMounted(() => {
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Enter' || event.keyCode === 13) {
            handle()
        }
    });
})
onUnmounted(() => {
    window.removeEventListener('keypress', handle);
})
</script>

<style lang="scss" scoped>
</style>
